from PySide6.QtWidgets import QWidget,QAbstractItemView,QMenu,QTableWidgetItem,QMessageBox
from PySide6.QtCore import Qt
import pandas as pd
from sqlalchemy.orm import Session
from settings.publicvar import engine
from settings.publicFuncation.exceldownloadimport import OperationModel
from views.usemodel.item import Ui_item
from views.person.model.person import PersonBaseInfo



class BankAccountView(QWidget,Ui_item):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.itemtable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.itemtable.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.itemtable.setContextMenuPolicy(Qt.CustomContextMenu)
        self.itemtable.customContextMenuRequested.connect(self.generate_menu)

        self.loadTableData()
        self.addbtn.clicked.connect(self.addFun)
        self.sereachedit.editingFinished.connect(self.serearchFun)
        self.serearchbtn.clicked.connect(self.serearchFun)
        self.downloadmodle.clicked.connect(self.downloadmodleFun)
        self.importbtn.clicked.connect(self.importdataFun)


        # 读取所有数据
    def loadTableData(self):
        with Session(engine) as session, session.begin():
            items = session.query(XXXX).all()
            self.setTableStructure(items)

    # 表格加载数据
    def setTableStructure(self, data):
        self.itemtable.setRowCount(len(data))
        for i, item in enumerate(data):
            idx = QTableWidgetItem(str(item.id))
            self.itemtable.setItem(i, 0, idx)
            name = QTableWidgetItem(item.bankinfo.name)
            self.itemtable.setItem(i, 1, name)
            bankname = QTableWidgetItem(item.bankname)
            self.itemtable.setItem(i, 2, bankname)
            bankcard = QTableWidgetItem(item.bankcard)
            self.itemtable.setItem(i, 3, bankcard)
            opencard = QTableWidgetItem(item.opencard)
            self.itemtable.setItem(i, 4, opencard)
            mark = QTableWidgetItem(item.mark)
            self.itemtable.setItem(i, 5, mark)


    def addFun(self):
        add = XXX('add',False)
        add.exec()
        self.loadTableData()

    # 获取表单
    def generate_menu(self,pos):
        menu = QMenu()
        viewitem = menu.addAction('查看')
        changeitem = menu.addAction('修改')
        deleteitm = menu.addAction('删除')
        action = menu.exec(self.bankcardtable.mapToGlobal(pos))
        posrow = self.bankcardtable.currentRow()
        columns = self.bankcardtable.columnCount()
        data = [self.bankcardtable.item(posrow, i).text() for i in range(columns)]
        for i in range(columns):
            item = self.bankcardtable.item(posrow,i)
            if item is None:
                data.append('')
            else:
                data.append(item.text())
        if action == viewitem:
            view = XXX('view', data)
            view.exec()
        elif action == changeitem:
            change = XXX('change', data)
            change.exec()
        elif action == deleteitm:
            delete = XXX('delete',data)
            delete.exec()
        self.loadTableData()

    # 搜索框数据处理
    def serearchFun(self):
        sereachdata = self.sereachedit.text().strip()
        if sereachdata == '':
            QMessageBox.critical(None, '错误', '搜索框不能为空！')
            self.loadTableData()
        else:
            with Session(engine) as session, session.begin():
                sereachName = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.name.like('%' + sereachdata + '%')).all()
                sereachIDcard = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.IDcard.like('%' + sereachdata + '%')).all()
                sereachiphone = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.iphone.like('%' + sereachdata + '%')).all()
                sereachData = sereachName + sereachIDcard + sereachiphone
                others = []
                if sereachData:
                    for personbase in sereachData:
                        for other in personbase.XXX:
                            others.append(other)
                else:
                    QMessageBox.critical(None,'没有数据','你搜索数据不存在！')
                self.setTableStructure(others)

    def downloadmodleFun(self):
        OperationModel().downloadmodleFun('XXX.xlsx')

    def importdataFun(self):
        items_names = ['idx','name','IDcard','bankname','bankcard','opencard','mark']
        dtypes = {'IDcard': str}
        data = OperationModel().importdataFun(items_names,dtypes)
        with (Session(engine) as session,session.begin()):
            exist_personbase = session.query(PersonBaseInfo).filter(PersonBaseInfo.IDcard.in_(data.IDcard.to_list())).all()
            if not exist_personbase:
                QMessageBox.critical(None,'失败','你导入的数据为空，不能导入空数据！')
            else:
                tem = []
                for item in exist_personbase:
                    personothers = item.personothers
                    if not personothers:
                        tem.append((item.IDcard,item.id))
                exist_personbase = tem
                exist_IDcard = [item[0] for item in exist_personbase]
                exist_personbase = pd.DataFrame(exist_personbase).rename(columns={1:'name_id',0:'IDcard'})
                save_items = data[data['IDcard'].isin(exist_IDcard)]
                save_items = pd.merge(exist_personbase, save_items, on='IDcard').drop(columns=['name', 'IDcard']).to_dict('records')
                items = [BankCard(**item) for item in save_items]
                session.add_all(items)
                QMessageBox.information(None, '提示', '你导入成功%s条，失败%s条，明细如下！' % (len(items), len(data) - len(items)))
        self.loadTableData()